/*
The MIT License

Copyright (c) 2010 Marco Ambu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

/* 
 * File:   MergeSort.h
 * Author: marco
 *
 * Created on December 7, 2009, 12:55 PM
 */

#ifndef _ALG_MERGESORT_H
#define	_ALG_MERGESORT_H

#include <alg/ISorter.h>
#include <alg/IComparer.h>
#include <algorithm>

namespace alg {

template <class Container>
class MergeSort : public ISorter
{
public:
  typedef typename Container::value_type ValueType;
  typedef typename Container::iterator Iterator;
private:
  typedef typename Container::difference_type Difference;

public:
    MergeSort(Container& container, const IComparer& comparer);

    // implement ISorter intf
    void sort();

private:
    void sort(const Iterator& begin, const Iterator& end);
    void merge(const Iterator& begin,
            const Iterator& middle,
            const Iterator& end);

private:
    Container& container_;
    const IComparer& comparer_;
};

template<class Container>
MergeSort<Container>::MergeSort(Container& container, const IComparer& comparer)
    : container_(container), comparer_(comparer)
{
}

template<class Container>
void MergeSort<Container>::sort()
{
    if (container_.size() < 2)
        return;

    this->sort(container_.begin(), container_.end());
}

template<class Container>
void MergeSort<Container>::sort(const Iterator& begin, const Iterator& end)
{
    if (!(begin < (end - 1)))
        return;

    Difference middle = (end - begin) / 2;

    sort(begin, begin + middle);
    sort(begin + middle, end);
#ifdef _USE_STD_MERGE
    std::inplace_merge(begin, begin + middle, end);
#else
    merge(begin, begin + middle, end);
#endif // _USE_STD_MERGE
}

template<class Container>
void MergeSort<Container>::merge(const Iterator& begin,
        const Iterator& middle,
        const Iterator& end)
{
    if (begin + 1 == middle && middle + 1 == end)
    {
        if (comparer_.isLess(*middle, *begin))//(*middle < *begin)
            std::swap(*begin, *middle); // in-place merge
        return;
    }
    // sequence begin -> middle is ordered, sequence middle + 1 -> end is ordered
    Iterator seq1 = begin;
    Iterator seq2 = middle;
    // TODO: try to implement in-place merge (instead of using an auxiliary container)
    Container aux;
    aux.reserve(middle - seq1);
    // skip already globally ordered items
    while (comparer_.isLess(*seq1, *seq2))
        ++seq1;
    Iterator aux_start = seq1;
    for ( ; seq1 < middle && seq2 < end; )
    {
        if (comparer_.isLess(*seq1, *seq2))//(*seq1 < *seq2)
        {
            aux.push_back(*seq1);
            ++seq1;
        }
        else
        {
            aux.push_back(*seq2);
            ++seq2;
        }
    }
    // copy remaining part of ordered sequence into target container
    for (Iterator it = end - (middle - seq1); seq1 < middle; ++seq1, ++it)
    {
        *it = *seq1;
    }
    //Container::iterator
    for (Iterator it = aux.begin(); it != aux.end(); ++it, ++aux_start)
    {
        *aux_start = *it;
    }
}

} // namespace alg

#endif	/* _ALG_MERGESORT_H */
